package com.winston.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;

/**
 * created by winston on 2024/4/3
 * CGLIB open in new window(Code Generation Library)是一个基于ASMopen in new window的字节码生成库，它允许我们在运行时对字节码进行修改和动态生成。
 * CGLIB 通过继承方式实现代理。很多知名的开源框架都使用到了CGLIBopen in new window，
 * 例如 Spring 中的 AOP 模块中：如果目标对象实现了接口，则默认采用 JDK 动态代理，否则采用 CGLIB 动态代理。
 */
public class CGProxy {
    static class CGTarget {

        public void doSomething (String msg) {
            System.out.println("do something : " + msg);
        }
    }

    public void doSomething (String msg) {
        System.out.println("do something : " + msg);
    }

    static class CGMethodInterceptor implements MethodInterceptor {

        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("before");
            Object result = methodProxy.invokeSuper(o, objects);
            System.out.println("after");
            return result;
        }
    }

    public static void main(String[] args) {
        CGMethodInterceptor cgMethodInterceptor = new CGMethodInterceptor();
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(CGProxy.class.getClassLoader());
        enhancer.setSuperclass(CGProxy.class);
        enhancer.setCallback(cgMethodInterceptor);
        CGProxy object = (CGProxy)enhancer.create();
        object.doSomething("test msg");

    }


}
